package com.huifai.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;

import java.util.HashSet;
import java.util.Set;

@Configuration
public class RedisConfigShaobing {

    private Logger logger = LoggerFactory.getLogger(RedisConfigShaobing.class);


    @Value("${redis.pool.maxTotal}")
    private Integer maxTotal;
    @Value("${redis.pool.maxIdle}")
    private Integer maxIdle;
    @Value("${redis.pool.testOnBorrow}")
    private Boolean testOnBorrow;
    @Value("${redis.pool.testOnReturn}")
    private Boolean testOnReturn;
    @Value("${redis.pool.maxWait}")
    private Long maxWait;
    @Value("${redis.password}")
    private String password;
    //    @Value("${redis.database}")
//    private Integer database;
    @Value("${spring.redis.cluster.nodes}")
    private String nodes;



    /**
     *
     * @date 2018/3/12 下午6:53
     * @return redis.clients.jedis.JedisPoolConfig
     * 初始化连接池配置对象
     *
     */
    @Bean(value = "jedisPoolConfig")
    public JedisPoolConfig initJedisPoolConfig(){
        JedisPoolConfig config = new JedisPoolConfig();

        //最大总量
        config.setMaxTotal(maxTotal);
        //设置最大空闲数量
        config.setMaxIdle(maxIdle);
        //设置最小空闲数量
        config.setMinIdle(maxIdle);
        //常规配置
        config.setTestOnBorrow(false);
        config.setTestOnReturn(true);
        return config;
    }

    /**
     *
     * @date 下午7:20
     * @return redis.clients.jedis.JedisSentinelPool
     * 生成JedisSentinelPool并且放入Spring容器
     *
     */
    @Bean(value = "sentinelPool")
    public JedisSentinelPool initJedisPool(@Qualifier(value = "jedisPoolConfig") JedisPoolConfig jedisPoolConfig){

        Set<String> nodeSet = new HashSet<>();
        //获取到节点信息
        String nodeString = nodes;
        //判断字符串是否为空
        if(nodeString == null || "".equals(nodeString)){
            throw new RuntimeException("RedisSentinelConfiguration initialize error nodeString is null");
        }
        String[] nodeArray = nodeString.split(",");
        //判断是否为空
        if(nodeArray == null || nodeArray.length == 0){
            throw new RuntimeException("RedisSentinelConfiguration initialize error nodeArray is null");
        }
        //循环注入至Set中
        for(String node : nodeArray){
            nodeSet.add(node);
        }
        //创建连接池对象
        JedisSentinelPool jedisPool = new JedisSentinelPool("master001" ,nodeSet ,jedisPoolConfig ,30000 , password);

        return jedisPool;
    }
}